//
//  OrderListVC.swift
//  旅航ios
//
//  Created by tulip on 2021/5/6.
//

import UIKit
import SwiftyJSON
import ESPullToRefresh
import HandyJSON
class OrderListVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var listData:JSON?
    var economyData:JSON?
    var businessData:JSON?
    var isJingjiCang=true
    var carrierLogo:String?
    var fromCtiy:String!
    var toCity:String!
    var data:JSON!
    var sendDic:Dictionary<String,Any>!
    var table: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let  headview =  HangbanHeadview.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: TopSpaceHeight))
        headview.setAddress1(address1: fromCtiy, address2: toCity)
        self.view.addSubview(headview)
        
        table=UITableView.init(frame: CGRect(x: 0, y: TopSpaceHeight, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-TopSpaceHeight))
        self.view.addSubview(table)
        table.backgroundColor=UIColor.init(hexString: "f1f2f6")
        table.delegate=self
        table.dataSource=self
        table.separatorStyle = .none
        table.showsVerticalScrollIndicator=false
        table.register(UINib(nibName: "OrderVCcell", bundle: nil), forCellReuseIdentifier: "OrderVCcell")
        table.register(UINib(nibName: "OrderCell", bundle: nil), forCellReuseIdentifier: "OrderCell")
        table.register(UINib(nibName: "CangWeiChooseCell", bundle: nil), forCellReuseIdentifier: "CangWeiChooseCell")
        table.estimatedRowHeight=100
        
        network()
        
        self.table.es.addPullToRefresh {
            self.network()
        }
       

        
        
        
    }
    
    func network(){
        Network.request(.searchPrice(parameters: sendDic)) { (JSON) in
            
            self.data=JSON["data"]
            self.economyData=JSON["data"]["vendors"]["economy"]
            self.businessData=JSON["data"]["vendors"]["business"]
            if self.isJingjiCang {
                self.listData=self.economyData
            }else{
                self.listData=self.businessData
            }
            self.table.reloadData()
            self.table.es.stopPullToRefresh()
        } failure: { (err) in
            
        }
    }
    
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        3
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 1{
            return 1
        }
        if section == 2 && data != nil{
            
            
            return listData?.count ?? 0
            
        }
        
        return   0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 20
        }
        if section == 2 {
            return 5
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 || section == 2{
            let head=UIView.init(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 20))
            head.backgroundColor=UIColor.init(hexString: "f1f2f6")
            return head
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0   {
            let cell:OrderVCcell=tableView.dequeueReusableCell(withIdentifier: "OrderVCcell", for: indexPath) as! OrderVCcell
            if data != nil{
            let AirlineName=data["com"].string ?? ""
            let CarrierNo=data["CarrierNo"].string ?? ""
            let Aircraft=data["Aircraft"].string ?? ""
            cell.name.text = AirlineName + CarrierNo + " " + Aircraft
            cell.time.text=data["date"].string
            cell.time1.text=data["btime"].string
            cell.time2.text=data["etime"].string
            let DepartAirport=data["depAirport"].string ?? ""
            let DepartTerminal=data["depTerminal"].string ?? ""
            cell.airport1.text=DepartAirport+DepartTerminal
            
            let ArriveAirport=data["arrAirport"].string ?? ""
            let ArriveTerminal=data["arrTerminal"].string ?? ""
            cell.airport2.text=ArriveAirport+ArriveTerminal
            cell.totalTime.text=data["FlightTime"].string
            cell.img.kf.setImage(with: URL(string:carrierLogo ?? ""))
       
                let ting=data["stopAirportName"].string ?? ""
                if ting != ""{
                    cell.ting.text="停 " + ting
                }
            }
            return cell
        }
        
        if indexPath.section == 1 {
            let cell:CangWeiChooseCell=tableView.dequeueReusableCell(withIdentifier: "CangWeiChooseCell") as! CangWeiChooseCell
            if isJingjiCang {
                cell.jingjiLine.backgroundColor=UIColor.init(hexString: "307cf8")
                cell.jingjiLab.textColor=UIColor.init(hexString: "307cf8")
                cell.jingjiPrice.textColor=UIColor.init(hexString: "307cf8")
                
                cell.toudengLine.backgroundColor=UIColor.clear
                cell.toudengLab.textColor=UIColor.init(hexString: "333333")
                cell.toudengPrice.textColor=UIColor.init(hexString: "333333")
               
            }else{
                cell.jingjiLine.backgroundColor=UIColor.clear
                cell.jingjiLab.textColor=UIColor.init(hexString: "333333")
                cell.jingjiPrice.textColor=UIColor.init(hexString: "333333")
                
                cell.toudengLine.backgroundColor=UIColor.init(hexString: "307cf8")
                cell.toudengLab.textColor=UIColor.init(hexString: "307cf8")
                cell.toudengPrice.textColor=UIColor.init(hexString: "307cf8")
            }
            
            cell.propChoose={[weak self](choose) in
                if choose {
                    self?.isJingjiCang=true
                    self?.listData=self?.economyData
                }else{
                    self?.isJingjiCang=false
                    self?.listData=self?.businessData
                }
                self?.table.reloadData()
            }
            
            if self.economyData?.count ?? 0 > 0 {

                guard let arr = JSONDeserializer<JJTickeModel>.deserializeModelArrayFrom(json: "\(self.economyData ?? "")")else {
                        return cell
                    
                }

                var min:Int = arr[0]!.barePrice
                var max:Int = arr[0]!.barePrice
                    
                for i in 0..<arr.count {
                    if arr[i]!.barePrice < min {
                        min = arr[i]!.barePrice
                    }
                    
                    if arr[i]!.barePrice > max {
                        max = arr[i]!.barePrice
                    }
                }
                
                
//                let price = self.economyData?[1]["barePrice"].int ?? 9999
                 cell.jingjiPrice.text="¥" + String(min) + "起"
            }else{
                cell.jingjiPrice.text="暂无报价"
            }
            
            
            
            
            if self.businessData?.count ?? 0 > 0{
                
                
                
                guard let arr = JSONDeserializer<JJTickeModel>.deserializeModelArrayFrom(json: "\(self.businessData ?? "")")else {
                        return cell
                    
                }
                
                var min:Int = arr[0]!.barePrice
                var max:Int = arr[0]!.barePrice
                    
                for i in 0..<arr.count {
                    if arr[i]!.barePrice < min {
                        min = arr[i]!.barePrice
                    }
                    
                    if arr[i]!.barePrice > max {
                        max = arr[i]!.barePrice
                    }
                }
                
                
//                let price = self.businessData?[0]["barePrice"].int ?? 9999
                 cell.toudengPrice.text="¥" + String(min) + "起"
            }else{
                cell.toudengPrice.text="暂无报价"
            }
            
            return cell
        }
        
        
        if indexPath.section == 2 {
            
            let cell:OrderCell=tableView.dequeueReusableCell(withIdentifier: "OrderCell", for: indexPath) as! OrderCell
            cell.fromCtiy=fromCtiy
            cell.toCity=toCity
       
            
            if data != nil {
                
                let departDate=data["date"].string ?? ""
                let depCode=sendDic["departCityCode"] ?? ""
                let arrCode=sendDic["arriveCityCode"] ?? ""
                let flightNo = sendDic["flightNo"] ?? ""
                let ticketPrice=String(listData?[indexPath.row]["vppr"].int ?? 9999)
                let barePrice=String(listData?[indexPath.row]["barePrice"].int ?? 9999)
                let productId=listData?[indexPath.row]["prtag"].string ?? ""
                let cabin=listData?[indexPath.row]["cabin"].string ?? ""
                cell.sendDic=["departDate":departDate,"departCityCode":depCode,"arriveCityCode":arrCode,"flightNo":flightNo,"ticketPrice":ticketPrice,"barePrice":barePrice,"productId":productId,"cabin":cabin]
                
                
                cell.price.text=String(listData?[indexPath.row]["barePrice"].int ?? 9999)
                cell.tip.text=listData?[indexPath.row]["tagProperty"].string
            let cabinCount=listData?[indexPath.row]["cabinCount"].string ?? ""
                if cabinCount == "A"{
                    cell.restTag.isHidden=true
                }else{
                    cell.restTag.text = "剩"  + cabinCount + "张"
                }
             let tagName=listData?[indexPath.row]["tagName"].string ?? ""
                if  tagName == "" {
                    cell.topTagView.isHidden=true
                }else{
                    cell.topTabLab.text=tagName
                }
             let sale = listData?[indexPath.row]["discount"].string ?? ""
             let cabinType=listData?[indexPath.row]["cabinType"].int
                switch cabinType {
                case 0:
                    cell.type.text="经济舱" + sale + "折"
                case 1:
                    cell.type.text="头等舱" + sale + "折"
                case 2:
                    cell.type.text="商务舱" + sale + "折"
                case 3:
                    cell.type.text="经济舱精选" + sale + "折"
                case 4:
                    cell.type.text="经济舱y舱" + sale + "折"
                case 5:
                    cell.type.text="超值头等舱" + sale + "折"
                default:
                    break
                }
            }
            return cell
        }
        return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section==0{
            return 170
        }
        if indexPath.section == 1 {
            return UITableView.automaticDimension
        }
        return 140
    }

}
